package com.wenjiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.dto.LoginParam;
import com.wenjiang.common.dto.RegisterParam;
import com.wenjiang.common.dto.UpdatePasswordParam;
import com.wenjiang.common.dto.UserInfoParam;
import com.wenjiang.common.exception.FileException;
import com.wenjiang.common.lang.Result;
import com.wenjiang.common.vo.AliLoginVo;
import com.wenjiang.common.vo.UserInfo;
import com.wenjiang.entity.AliPayUser;
import com.wenjiang.entity.MallUser;
import com.wenjiang.mapper.MallUserMapper;
import com.wenjiang.service.MallUserService;
import com.wenjiang.common.util.JWTUtil;
import com.wenjiang.common.util.Md5Utils;
import com.wenjiang.util.OSSUtils;
import com.wenjiang.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwj
 * @since 2021-07-20
 */
@Service
@Slf4j
public class MallUserServiceImpl extends ServiceImpl<MallUserMapper, MallUser> implements MallUserService {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OSSUtils ossUtils;

    @Override
    public Result registerUser(RegisterParam registerParam) {
        String truecode = (String) redisUtils.get(RedisKey.registerCodeKey + registerParam.getUserEmail());
        //对比验证码
        if(!registerParam.getCode().equals(truecode)){
            return Result.fail(500,"验证码不正确");
        }

        //查询是否注册过
        int count = count(new QueryWrapper<MallUser>().eq("user_name", registerParam.getUserName()));

        if(count>0){
           return Result.fail(500,"用户注册过了");
        }


        try {
            //插入数据库
            MallUser mallUser= new MallUser();
            BeanUtil.copyProperties(registerParam,mallUser);
            //密码加密
            mallUser.setPassword(Md5Utils.MD5Encode(mallUser.getPassword()));
            save(mallUser);

        }catch (Exception e){
            log.error(e.getMessage());

            return Result.fail(500,"系统异常");
        }





        return Result.succ("注册成功");
    }

    @Override
    public Result loginUser(LoginParam loginParam) {

        //根据名称查询
        MallUser mallUser = baseMapper.selectOne(new QueryWrapper<MallUser>().eq("user_name",
                loginParam.getUserName()));
        //判断是否为空
        if(mallUser==null){
            return  Result.fail("500","用户不存在");
        }

        // 判断密码是否正确
        if (!Md5Utils.MD5Encode(loginParam.getPassword()).equals(mallUser.getPassword())){
            return Result.fail("500","密码错误");
        }

        //构建VO 不返回密码 加强安全性
        UserInfo vo = new UserInfo();
        BeanUtil.copyProperties(mallUser,vo);

        String token = JWTUtil.createToken(vo.getUserId());

        vo.setToken(token);


        return Result.succ(vo,"登录成功");
    }


    @Override
    public AliLoginVo aliPayLoginUser(AliPayUser aliPayUser) {
        //查询之前有没有用支付宝登陆过
        MallUser mallUser = baseMapper.selectOne(new QueryWrapper<MallUser>().eq("ali_pay_id",
                aliPayUser.getAliPayId()));

        AliLoginVo userInfo = new AliLoginVo();

        //有登陆过 直接返回信息  //构建jwt token
        if(mallUser!=null){
            //构建token
            String token = JWTUtil.createToken(mallUser.getUserId());
            //构建用户token
            userInfo.setToken(token);
            return userInfo;
        }


        //没有登陆过 新建插入一条数据 一些数据
        mallUser= new MallUser();
        mallUser.setAliPayId(aliPayUser.getAliPayId());
        mallUser.setUserImgUrl(aliPayUser.getUserImgUrl());
        mallUser.setName(aliPayUser.getAliPayId());
        mallUser.setUserName(aliPayUser.getAliPayId());
        mallUser.setCreateTime(LocalDateTime.now());
        //支付宝用户默认密码;
        mallUser.setPassword(Md5Utils.MD5Encode("123456"));

        baseMapper.insert(mallUser);

        BeanUtil.copyProperties(mallUser,userInfo);
        //获取主键id
        Long userId = mallUser.getUserId();

        //构建token
        String token = JWTUtil.createToken(userId);

        //设置相关参数
        userInfo.setToken(token);

        return userInfo;
    }


    @Override
    public Result getUserInfo(Long userId) {

        UserInfo userInfo= new UserInfo();
        MallUser mallUser = baseMapper.selectById(userId);

        BeanUtil.copyProperties(mallUser,userInfo);

        return  Result.succ(userInfo);
    }

    //更新用户信息
    @Override
    public Result updateUserInfo(UserInfoParam userInfoParam,Long userId) {

        //更新基本信息

        UpdateWrapper updateWrapper= new UpdateWrapper();
        updateWrapper.set("name",userInfoParam.getName());
        updateWrapper.set("user_sign",userInfoParam.getUserSign());
        updateWrapper.set("user_email",userInfoParam.getUserEmail());
        updateWrapper.set("user_phone",userInfoParam.getUserPhone());
        updateWrapper.eq("user_id",userId);


        int i = baseMapper.update(null, updateWrapper);
        if(i>0){
            return Result.succ("更新成功");
        }

        return Result.fail(500,"更新失败");
    }

    @Override
    public Result updateUserImg(MultipartFile file, String name, Long userId) {

        //拼接完整路径
        String path= "userImg/"+name;

        try {

            //获取字节码
            byte[] bytes = file.getBytes();

            //上传文件（简单上传）

            ossUtils.upload(bytes,path);

            //生成访问的url
            String url = ossUtils.getUrl(path);

            //对数据库进行更新操作 (可投递到消息对列)

            UpdateWrapper updateWrapper= new UpdateWrapper();

            updateWrapper.set("user_img_url",url);
            updateWrapper.eq("user_id",userId);

            baseMapper.update(null,updateWrapper);

            return Result.succ(url,"文件上传成功!");

        }catch (Exception e){
            throw new FileException();
        }

    }

    //更新用户密码

    @Override
    public Result updateUserPassword(UpdatePasswordParam updatePasswordParam,Long userId) {
        //比较邮箱验证码
        Object code = redisUtils.get(RedisKey.updatePasswordKey + userId.toString());
        if(!updatePasswordParam.getCode().equals(code)){
            return Result.fail("邮箱验证码错误");
        }
        //比较旧密码
        MallUser mallUser = baseMapper.selectById(userId);
        String oldPassword = Md5Utils.MD5Encode(updatePasswordParam.getOldPassword()) ;
        if(!mallUser.getPassword().equals(oldPassword)){
            return Result.fail("输入的旧密码不正确，请重试");
        }

        //更新成新密码

        UpdateWrapper updateWrapper = new UpdateWrapper();

        updateWrapper.set("password",Md5Utils.MD5Encode(updatePasswordParam.getNewPassword()));

        updateWrapper.eq("user_id",userId);

        baseMapper.update(null,updateWrapper);

        return Result.succ("密码重置成功");
    }
}
